<template>
	<view class="comment-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content">
				<view class="back-btn" @click="back">
					<view class="back-arrow-icon"></view>
				</view>
				<view class="navbar-title">我的点评</view>
				<view class="navbar-right"></view>
			</view>
		</view>
		
		<!-- 分类切换 -->
		<view class="tabs-section">
			<view class="tab-item" 
			      :class="{ active: currentTab === 0 }" 
			      @click="switchTab(0)">
				全部
			</view>
			<view class="tab-item" 
			      :class="{ active: currentTab === 1 }" 
			      @click="switchTab(1)">
				景区
			</view>
			<view class="tab-item" 
			      :class="{ active: currentTab === 2 }" 
			      @click="switchTab(2)">
				酒店
			</view>
		</view>
		
		<!-- 点评列表 -->
		<view class="list-section">
			<view v-if="loading" class="loading-section">
				<u-loading-icon mode="spinner"></u-loading-icon>
				<text class="loading-text">加载中...</text>
			</view>
			
			<view v-else-if="commentList.length === 0" class="empty-section">
				<u-empty mode="data" text="暂无点评"></u-empty>
			</view>
			
			<view v-else class="comment-list">
				<view class="comment-item" v-for="(item, index) in commentList" :key="item.commentId || index">
					<image class="item-image" :src="getImageUrl(item)" mode="aspectFill" @click="goToDetail(item)"></image>
					<view class="item-content" @click="goToDetail(item)">
						<view class="item-title-row">
							<view class="item-title">{{ item.title || '未知' }}</view>
						</view>
						<view class="item-rating-row">
							<u-rate 
								:value="item.rate || 0" 
								:count="5" 
								:size="24" 
								:disabled="true"
								active-color="#ff9500"
								inactive-color="#e5e5e5">
							</u-rate>
							<text class="rating-text">{{ item.rate || 0 }}分</text>
						</view>
						<view class="item-content-text">
							{{ item.content || '暂无内容' }}
						</view>
						<view class="item-images" v-if="item.images">
							<image 
								v-for="(img, imgIndex) in getImageList(item.images)" 
								:key="imgIndex"
								class="comment-image"
								:src="img" 
								mode="aspectFill"
								@click.stop="previewImage(img, getImageList(item.images))">
							</image>
						</view>
						<view class="item-footer">
							<text class="item-time">{{ formatTime(item.createTime) }}</text>
							<view class="item-stats">
								<text class="stat-item" v-if="item.likeCount">👍 {{ item.likeCount }}</text>
								<text class="stat-item" v-if="item.replyCount">💬 {{ item.replyCount }}</text>
							</view>
						</view>
					</view>
				</view>
				<!-- 底部提示 -->
				<view class="list-end-tip" v-if="commentList.length > 0">
					<view class="end-line"></view>
					<text class="end-text">到底了哦</text>
					<view class="end-line"></view>
				</view>
			</view>
		</view>
		
		<u-toast ref="uToast" />
	</view>
</template>

<script>
import $api from '../../api/user.js';

export default {
	data() {
		return {
			userId: null,
			currentTab: 0, // 0-全部，1-景区，2-酒店
			commentList: [],
			loading: false,
			defaultImage: '/static/image/user/avatar.jpg',
			statusBarHeight: 0
		}
	},
	onLoad() {
		// 获取状态栏高度
		const systemInfo = uni.getSystemInfoSync();
		this.statusBarHeight = systemInfo.statusBarHeight || 0;
		
		this.loadUserInfo();
		this.loadCommentList();
	},
	onShow() {
		// 页面显示时刷新列表
		this.loadCommentList();
	},
	methods: {
		// 加载用户信息
		loadUserInfo() {
			const user = uni.getStorageSync('user');
			if (!user || !user.id) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1500);
				return;
			}
			
			this.userId = user.id;
		},
		
		// 切换分类
		switchTab(tab) {
			this.currentTab = tab;
			this.loadCommentList();
		},
		
		// 加载点评列表
		loadCommentList() {
			if (!this.userId) {
				return;
			}
			
			this.loading = true;
			
			const params = {
				userId: this.userId
			};
			
			// 如果选择了特定类型，添加类型参数
			if (this.currentTab === 1) {
				params.targetType = 1; // 景区
			} else if (this.currentTab === 2) {
				params.targetType = 2; // 酒店
			}
			
			$api.getCommentList(params).then(res => {
				this.loading = false;
				
				if (res.data && res.data.code === 200) {
					this.commentList = res.data.data || [];
				} else {
					this.$refs.uToast.show({
						title: res.data?.message || '获取点评列表失败',
						type: 'error',
					});
				}
			}).catch(err => {
				this.loading = false;
				console.error('获取点评列表失败', err);
				this.$refs.uToast.show({
					title: '获取点评列表失败，请重试',
					type: 'error',
				});
			});
		},
		
		// 跳转到详情页
		goToDetail(item) {
			if (item.targetType === 1) {
				// 景区详情
				uni.navigateTo({
					url: `/pages/index/detail?id=${item.targetId}&type=scenic`
				});
			} else if (item.targetType === 2) {
				// 酒店详情
				uni.navigateTo({
					url: `/pages/index/detail?id=${item.targetId}&type=hotel`
				});
			}
		},
		
		// 获取图片URL（处理JSON格式的photos字段）
		getImageUrl(item) {
			if (!item.imageUrl) {
				return this.defaultImage;
			}
			
			// 如果是JSON格式的字符串，尝试解析
			if (item.imageUrl.startsWith('[') || item.imageUrl.startsWith('"')) {
				try {
					const photos = JSON.parse(item.imageUrl);
					if (Array.isArray(photos) && photos.length > 0) {
						return photos[0];
					}
				} catch (e) {
					console.warn('解析图片JSON失败', e);
				}
			}
			
			return item.imageUrl || this.defaultImage;
		},
		
		// 获取图片列表（处理逗号分隔或JSON格式）
		getImageList(images) {
			if (!images) return [];
			
			// 尝试解析JSON
			if (images.startsWith('[') || images.startsWith('"')) {
				try {
					const parsed = JSON.parse(images);
					if (Array.isArray(parsed)) {
						return parsed;
					}
				} catch (e) {
					// 不是JSON，继续处理
				}
			}
			
			// 尝试按逗号分隔
			if (images.includes(',')) {
				return images.split(',').filter(img => img.trim());
			}
			
			// 单个图片
			return [images];
		},
		
		// 预览图片
		previewImage(current, urls) {
			uni.previewImage({
				current: current,
				urls: urls
			});
		},
		
		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return '';
			
			const date = new Date(timeStr);
			const now = new Date();
			const diff = now.getTime() - date.getTime();
			const days = Math.floor(diff / (1000 * 60 * 60 * 24));
			
			if (days === 0) {
				return '今天';
			} else if (days === 1) {
				return '昨天';
			} else if (days < 7) {
				return days + '天前';
			} else {
				const month = date.getMonth() + 1;
				const day = date.getDate();
				return `${month}-${day}`;
			}
		},
		
		back() {
			// 返回到"我的"界面（tabBar页面）
			uni.switchTab({
				url: '/pages/user/user'
			});
		}
	}
}
</script>

<style lang="scss" scoped>
page {
	background-color: #f5f5f5;
}

.comment-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-top: 88rpx;
}

.custom-navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 991;
	background-color: #fff;
	border-bottom: 1rpx solid #e5e5e5;
	
	.navbar-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 88rpx;
		padding: 0 20rpx;
		
		.back-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 60rpx;
			height: 60rpx;
			padding: 0;
			position: relative;
			z-index: 1;
			
			.back-arrow-icon {
				width: 20rpx;
				height: 20rpx;
				border-left: 3rpx solid #606266;
				border-bottom: 3rpx solid #606266;
				transform: rotate(45deg);
			}
		}
		
		.navbar-title {
			flex: 1;
			text-align: center;
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
		
		.navbar-right {
			width: 60rpx;
		}
	}
}

.tabs-section {
	display: flex;
	background-color: #fff;
	padding: 0;
	border-bottom: 1rpx solid #e5e5e5;
	
	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		color: #333;
		padding: 24rpx 0;
		position: relative;
		
		&.active {
			color: #333;
			font-weight: bold;
			
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 60rpx;
				height: 4rpx;
				background-color: #3c9cff;
				border-radius: 2rpx;
			}
		}
	}
}

.list-section {
	padding: 0;
	background-color: #fff;
}

.loading-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
	
	.loading-text {
		margin-top: 20rpx;
		font-size: 26rpx;
		color: #999;
	}
}

.empty-section {
	padding: 100rpx 0;
}

.comment-list {
	.comment-item {
		display: flex;
		background-color: #fff;
		border-radius: 0;
		margin-bottom: 0;
		padding: 30rpx 20rpx;
		border-bottom: 1rpx solid #f5f5f5;
		
		.item-image {
			width: 200rpx;
			height: 200rpx;
			flex-shrink: 0;
			border-radius: 8rpx;
			background-color: #f5f5f5;
		}
		
		.item-content {
			flex: 1;
			padding-left: 20rpx;
			display: flex;
			flex-direction: column;
			justify-content: flex-start;
			min-height: 200rpx;
			
			.item-title-row {
				margin-bottom: 12rpx;
				
				.item-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					line-height: 1.5;
				}
			}
			
			.item-rating-row {
				display: flex;
				align-items: center;
				margin-bottom: 12rpx;
				
				.rating-text {
					margin-left: 12rpx;
					font-size: 24rpx;
					color: #ff9500;
					font-weight: 500;
				}
			}
			
			.item-content-text {
				font-size: 26rpx;
				color: #666;
				line-height: 1.6;
				margin-bottom: 12rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 3;
				-webkit-box-orient: vertical;
			}
			
			.item-images {
				display: flex;
				flex-wrap: wrap;
				gap: 10rpx;
				margin-bottom: 12rpx;
				
				.comment-image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 8rpx;
					background-color: #f5f5f5;
				}
			}
			
			.item-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: auto;
				
				.item-time {
					font-size: 22rpx;
					color: #999;
				}
				
				.item-stats {
					display: flex;
					gap: 20rpx;
					
					.stat-item {
						font-size: 22rpx;
						color: #999;
					}
				}
			}
		}
	}
	
	.list-end-tip {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0;
		
		.end-line {
			flex: 1;
			height: 1rpx;
			background-color: #e5e5e5;
		}
		
		.end-text {
			margin: 0 20rpx;
			font-size: 24rpx;
			color: #999;
		}
	}
}
</style>

